#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>

#define NUM 16


//int main(int argc, char *argv[], char *env[])
int main(void)
{
    pid_t id=fork();
    if(id<0)
    {
        return -1;
    }
    else if(id==0)//子进程
    {
        printf("子进程开始运行，pid:%d\n",getpid());
        //在子进程中使用进程替换
        //ls -a -l
       
        //execlp("ls","ls","-a","-l",NULL);

        char *const _argv[NUM] = {
            (char*)"ls",(char*)"--color=auto",(char*)"-a",(char*)"-l",(char*)"-i", NULL};
        execvp("ls",_argv);
        //execv("/usr/bin/ls", _argv);
    
        //char *const argv[] = {"ps", "-ef", NULL};
        //execv("/bin/ps",argv);

        //execl("/usr/bin/ls","ls","-a","-l",NULL);
        exit(-2);//进程替换失败
    }
    else//父进程 
    {
        printf("父进程开始运行，pid:%d\n",getpid());
        //让父进程阻塞式等待子进程：子进程运行完毕，父进程获取后才退出，保证运行时的顺序(PS:单独fork，父子进程顺序具有不确定性)
        int status=0;
        pid_t ret=waitpid(-1,&status,0);//参数：等待任意一个子进程、获取进程状态、阻塞式等待
        if(ret)
            printf("wait success, exit code:%d\n",WEXITSTATUS(status));

    }
    return 0;
}
